//
//  LoanSubmitViewController.swift
//  jiuzhoudai
//
//  Created by 卢小艳 on 2025/7/15.
//

import Foundation
import UIKit
import CleanJSON


class JQFXHMoliLoanSubmitxxViewController: HJYJBaseViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    var jqfxhParaaaDic : [String: String] = [:]
    var jqfxhLastyyPara : [String: String] = [:]
    var jqfxhListzzs: [JQFXHLoanListuuItemModel] = []
    
    var jqfxhApplicationbbResponse: JQFXHLoanApplicationnnResponse?
    
    init(para: [String: String]) {
        self.jqfxhLastyyPara = para
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     override func viewDidLoad() {
        super.viewDidLoad()
        
         title = "申请额度"
        
         self.view.backgroundColor = UIColor.jqfxhTextLightaaGray
        
         guard let url = Bundle.main.url(forResource: "jqfxhMoliLoanwwlist", withExtension: "json"),
               let data = try? Data(contentsOf: url) else {
             print("无法加载地址数据文件")
             return
         }
         
         do {
             let listData = try CleanJSONDecoder().decode(JQFXHLoanvvListModel.self, from: data)
             self.jqfxhListzzs = listData.array
         } catch {
             print("解析地址数据失败: \(error)")
         }
         
         
         
         jqfxhSetupccUI()
    }
    
    
    @objc func jqfxhUploadLoan() {
        JQFXHHUD.jqfxhShowssLoading()
        let merged = jqfxhParaaaDic.merging(jqfxhLastyyPara) { (_, new) in new }
        let provider = JQFXHNetworkManager.shared.moliProvider
        JQFXHNetworkManager.shared.jqfxhRequest(provider: provider, target: .jqfxhLoanmApply(dic: merged),type: JQFXHLoanApplicationnnResponse.self) { result in
            JQFXHHUD.jqfxhHttidden()
            switch result {
            case.success(let data):
                let jqfxhLoaneeRes = data
                self.jqfxhApplicationbbResponse = jqfxhLoaneeRes
                if !jqfxhLoaneeRes.matchInfo.productInfo.name.isEmpty && jqfxhLoaneeRes.matchInfo.agreementList.count > 0 {
                    //获取协议
                    let jqfxhFirstAgreeMent = jqfxhLoaneeRes.matchInfo.agreementList.first
                    self.getprotocahhlInfo(code: jqfxhFirstAgreeMent?.code ?? "", formId: jqfxhLoaneeRes.formId, productId: jqfxhLoaneeRes.matchInfo.productId)
                }else {
                    self.jqfxhToLoanffSuccess()
                }
               
            case .failure(let error):
                print(error)
            }
        }
        
        
    }
    
    func jqfxhToLoanffSuccess() {
        let successggvc = JQFXHLoanSuccessxxController.init()
        self.navigationController?.pushViewController(successggvc, animated: true)
    }
    
    func jqfxhMlConfirmkkSubmit() {
        let providellr = JQFXHNetworkManager.shared.moliProvider
        JQFXHNetworkManager.shared.jqfxhRequest(provider: providellr, target: .jqfxhCuuonfirm(stepId: jqfxhApplicationbbResponse?.matchInfo.stepId ?? "", productId: String(jqfxhApplicationbbResponse?.matchInfo.productId ?? 0))) { result in
            JQFXHHUD.jqfxhHttidden()
            switch result {
            case.success(_):
                self.jqfxhToLoanffSuccess()
            case .failure(let error):
                print(error)
            }
        }
       
    }
    
    
    func getprotocahhlInfo(code:String, formId:String, productId:Int) {
        let provider = JQFXHNetworkManager.shared.moliProvider
        JQFXHNetworkManager.shared.jqfxhRequest(provider: provider, target: .jqfxhGetttProtocols(code: code, form_id: formId, product_id: String(productId)),type: JQFXHProtocolInfoooData.self) { result in
            JQFXHHUD.jqfxhHttidden()
            switch result {
            case.success(let data):
                let infoiiData = data
                let content = infoiiData.content
                let webjj = JQFXHWebViewController.init(jqfxhUrlccString: content, jqfxhTitle: "协议")
                webjj.block = {[weak self] _ in
                    self?.jqfxhMlConfirmkkSubmit()
                }
                self.present(webjj, animated: true)
            case .failure(let error):
                print(error)
            }
        }
       
    }
    
   
    
    
     private func jqfxhSetupccUI() {
         self.view.backgroundColor = UIColor.jqfxhBigViewBgccGray
         self.view.addSubview(jqfxhSubmitddButton)
         jqfxhSubmitddButton.snp.makeConstraints { make in
             make.left.equalTo(self.view).offset(28)
             make.right.equalTo(self.view).offset(-28)
             make.bottom.equalTo(self.view).offset(-UIApplication.shared.jqfxhSafeAreaInsets.bottom-60)
             make.height.equalTo(42)
         }
         
         self.view.addSubview(jqfxhMoneyCompanymmLabel)
         jqfxhMoneyCompanymmLabel.snp.makeConstraints { make in
             make.centerX.equalTo(self.view)
             make.top.equalTo(jqfxhSubmitddButton.snp.bottom).offset(15)
         }
         
         self.view.addSubview(jqfxhCollectionnnView)
         jqfxhCollectionnnView.snp.makeConstraints { make in
             make.left.equalTo(16)
             make.right.equalTo(-16)
             make.top.equalTo(16)
             make.bottom.equalTo(jqfxhSubmitddButton.snp.top).offset(-16)
         }
    }
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        self.jqfxhListzzs.count
    }
    
   
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        if section == self.jqfxhListzzs.count-1 {
            return CGSize(width: jqfxhScreenWidth, height: 16)

        }
        return CGSize(width: jqfxhScreenWidth, height: CGFLOAT_MIN)
    }
    
    
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.jqfxhListzzs[section].list.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        if kind == UICollectionView.elementKindSectionHeader {
            
            let head = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: JQFXHLoanSectionyyHeaderId, for: indexPath) as! JQFXHLoanSectionyyHeader
            head.updateWithSectionModel(model: self.jqfxhListzzs[indexPath.section])
            return head
           
            
        }else{
            let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "foot", for: indexPath)
            return footerView
        }
    }
   
    
    
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: JQFXHLoanItemwwCellId, for: indexPath) as! JQFXHLoanItemwwCell
        cell.jqfxhUpdateWithItemxxModel(model: self.jqfxhListzzs[indexPath.section].list[indexPath.item])
        return cell
        
    }
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        return CGSize(width: jqfxhScreenWidth-36-32, height:45)
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var sectionModel = self.jqfxhListzzs[indexPath.section]

        if indexPath.section == 0 {
            for index in 0..<sectionModel.list.count{
                var itemModel = sectionModel.list[index]
                if index == indexPath.row {
                    itemModel.isSlected = true
                    jqfxhParaaaDic[sectionModel.key] = itemModel.itemId
                }else {
                    itemModel.isSlected = false
                }
                sectionModel.list[index] = itemModel
            }
            self.jqfxhListzzs[indexPath.section] = sectionModel
        }else {
            var itemModel = sectionModel.list[indexPath.row]
            itemModel.isSlected = !itemModel.isSlected
            sectionModel.list[indexPath.row] = itemModel
            self.jqfxhListzzs[indexPath.section] = sectionModel
            var zonghe : [JQFXHSelectedItemttModel] = []
            for item in sectionModel.list{
                if item.isSlected {
                    zonghe.append(item)
                }
            }
            jqfxhParaaaDic[sectionModel.key] = zonghe.map { "\($0.itemId)" }.joined(separator: ",")
        }
        
        self.jqfxhCollectionnnView.reloadData()
    }
    
    private lazy var jqfxhLayout: UICollectionViewFlowLayout = {
        let jqfxhLayout = UICollectionViewFlowLayout()
        jqfxhLayout.minimumLineSpacing = 12
        jqfxhLayout.minimumInteritemSpacing = 12
        jqfxhLayout.scrollDirection = .vertical
        jqfxhLayout.itemSize = CGSize(width: (jqfxhScreenWidth-56-32)/3, height: 26)
        jqfxhLayout.sectionInset = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)
        return jqfxhLayout
    }()
    
    
    
    
    lazy var jqfxhMoneyCompanymmLabel : UILabel = {
        let jqfxhMoneyCompanymmLabel = UILabel()
        jqfxhMoneyCompanymmLabel.text = JQFXHCompanyMessage.jqfxhZhongMoneyCompanyName
        jqfxhMoneyCompanymmLabel.font = UIFont.jqfxhMedium13
        jqfxhMoneyCompanymmLabel.textColor = UIColor.jqfxhTextLightaaGray
        return jqfxhMoneyCompanymmLabel
    }()
    
    lazy var jqfxhSubmitddButton: UIButton = {
        let jqfxhSubmitddButton = UIButton(type: .custom)
        jqfxhSubmitddButton.setTitle("提交申请", for: .normal)
        jqfxhSubmitddButton.backgroundColor = UIColor.jqfxhThemexxRed
        jqfxhSubmitddButton.setTitleColor(.white, for: .normal)
        jqfxhSubmitddButton.layer.cornerRadius = 8
        jqfxhSubmitddButton.addTarget(self, action: #selector(jqfxhUploadLoan), for: .touchUpInside)
        return jqfxhSubmitddButton
    }()
    
    
    public lazy var jqfxhCollectionnnView: UICollectionView = {
        
        let jqfxhCollectionnnView = UICollectionView(frame: .zero, collectionViewLayout: self.jqfxhLayout)
        jqfxhCollectionnnView.backgroundColor = UIColor.white

        jqfxhCollectionnnView.register(JQFXHLoanItemwwCell.self, forCellWithReuseIdentifier: JQFXHLoanItemwwCellId)
        jqfxhCollectionnnView.register(JQFXHLoanSectionyyHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: JQFXHLoanSectionyyHeaderId)
                
        jqfxhCollectionnnView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "foot")

        jqfxhCollectionnnView.showsVerticalScrollIndicator = false
        jqfxhCollectionnnView.showsHorizontalScrollIndicator = false
        jqfxhCollectionnnView.layer.cornerRadius = 12
        jqfxhCollectionnnView.layer.masksToBounds = true
        if #available(iOS 11.0, *) {
            jqfxhCollectionnnView.contentInsetAdjustmentBehavior = .never
        }
        jqfxhCollectionnnView.alwaysBounceVertical = true
        jqfxhCollectionnnView.delegate = self
        jqfxhCollectionnnView.dataSource = self
        return jqfxhCollectionnnView
    }()
    
    
}





